<template>
  <div class="app-container home">
    <el-row :gutter="10" class="xxx" style="width: 100%; padding-bottom: 10px">
      <el-col :span="5" style="align-items: center;">
        <el-card class="card-wrap">
          <div class="left-box left-box1">
            <img src="@/assets/images/item-icon1.png" alt="" />
          </div>
          <div class="right-box">
            <el-statistic :value="schoolStatInfo.studentNum" :value-style="[{ 'font-size': '50px' }, { 'align-content': 'center' }]" />
            <span>全校学生人数</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card class="card-wrap">
          <div class="left-box left-box2">
            <img src="@/assets/images/item-icon2.png" alt="" />
          </div>
          <div class="right-box">
            <el-statistic :value="schoolStatInfo.staffNum" :value-style="[{ 'font-size': '50px' }, { 'align-content': 'center' }]" />
            <span>全校教职工人数</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5" style="align-items: center">
        <el-card class="card-wrap">
          <div class="left-box left-box3">
            <img src="@/assets/images/item-icon3.png" alt="" />
          </div>
          <div class="right-box">
            <el-statistic :value="schoolStatInfo.roomMemberNum" :value-style="[{ 'font-size': '50px' }, { 'align-content': 'center' }]" />
            <span>全校住宿生人数</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card class="card-wrap">
          <div class="left-box left-box4">
            <img src="@/assets/images/item-icon4.png" alt="" />
          </div>
          <div class="right-box">
            <el-statistic :value="schoolStatInfo.classNum" :value-style="[{ 'font-size': '50px' }, { 'align-content': 'center' }]" />
            <span>全校班级数</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4" style="align-items: center">
        <el-card class="card-wrap" style="margin-right: -10px;">
          <div class="left-box left-box5">
            <img src="@/assets/images/item-icon5.png" alt="" />
          </div>
          <div class="right-box">
            <el-statistic :value="schoolStatInfo.leaveNum" :value-style="[{ 'font-size': '50px' }, { 'align-content': 'center' }]" />
            <span>今日请假人数</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row class="main">
      <el-col :span="24">
        <el-card class="main-wrap">
          <el-tabs v-model="activeName" @tab-click="handleClick" class="demo-tabs">
            <el-tab-pane label="今日学校学生考勤实时统计" :name="'student'">
              <el-row>
                <el-col :span="5">
                  <el-statistic
                    :value="schoolStatInfo.studentNum"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">学生总数</span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px">人</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="4">
                  <el-statistic
                    :value="studentAttendanceStatInfo.attendanceNum"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">
                        <template v-if="studentStatOption.startsWith('start')"> 应到 </template>
                        <template v-else> 应离 </template>
                      </span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px">人</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="4">
                  <el-statistic
                    :value="studentAttendanceStatInfo.presenceNum"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">
                        <template v-if="studentStatOption.startsWith('start')"> 实到 </template>
                        <template v-else> 实离 </template>
                      </span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px">人</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="5">
                  <el-statistic
                    :value="studentAttendanceStatInfo.presenceCentage"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">
                        <template v-if="studentStatOption.startsWith('start')"> 到校率 </template>
                        <template v-else> 离校率 </template>
                      </span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px; color: #57a3f3">%</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="studentStatOption"
                    @change="() => {
      loadStudentAttendanceStat(studentStatOption);
      loadGradeAttendanceStat(studentStatOption);
    }"
                    style="width: 160px"
                  >
                    <el-option v-for="dict in student_stat_options" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <div ref="studentAttendanceStatPieRef" style="height: 265px; width: 600px; vertical-align: center" />
                  <div ref="studentAttendanceRateLineRef" style="height: 265px; width: 600px; vertical-align: center" />
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="今日宿舍考勤实时统计" :name="'dormitory'">
              <el-row>
                <el-col :span="5">
                  <el-statistic
                    :value="schoolStatInfo.roomMemberNum"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">住宿总人数</span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px">人</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="5">
                  <el-statistic
                    :value="dormitoryStatInfo.ycqCount"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">应{{ dormitoryStatType }}寝人数</span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px">人</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="5">
                  <el-statistic
                    :value="dormitoryStatInfo.cqCount"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">{{ dormitoryStatType }}寝人数</span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px">人</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="5">
                  <el-statistic
                    :value="dormitoryStatInfo.presenceCentage"
                    :value-style="[{ 'font-size': '30px' }, { 'align-content': 'center' }, { 'color': '#57a3f3' }]"
                  >
                    <template #prefix>
                      <span style=" font-size: 14px">{{ dormitoryStatType }}寝率</span>
                    </template>
                    <template #suffix>
                      <span style=" font-size: 14px; color: #57a3f3">%</span>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="dormitoryStatOption"
                    @change="() => {
      loadShiftStat(dormitoryStatOption);
      loadBuildingShiftStat(dormitoryStatOption);
    }"
                  >
                    <el-option v-for="dict in attendance_shift" :key="dict.value" :label="dict.label" :value="Number(dict.value)"></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <div ref="dormitoryAttendanceStatPieRef" style="height: 265px; width: 600px; vertical-align: center" />
              <div ref="dormitoryAttendanceRateLineRef" style="height: 265px; width: 600px; vertical-align: center" />
            </el-tab-pane>
          </el-tabs>
          <div style="width: 500px">
            <el-row>
              <el-col style="text-align: center">
                <div class="r-title">今日考勤统计情况</div>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="width: 100%;padding: 10px 40px;">
              <el-col :span="5" style="text-align: center">
                <el-statistic
                  :value="attendanceStatInfo.presenceNum"
                  :value-style="[{ 'font-size': '30px' }]"
                  :formatter="(val) => { return attendanceStatInfo.attendanceNum + '/' + val }"
                />
                <span>应到/实到</span>
              </el-col>
              <el-col :span="5" style="text-align: center">
                <el-statistic :value="attendanceStatInfo.absenceNum" :value-style="[{ 'font-size': '30px' }]" />
                <span>缺勤</span>
              </el-col>
              <el-col :span="5" style="text-align: center">
                <el-statistic :value="attendanceStatInfo.leaveNum" :value-style="[{ 'font-size': '30px' }]" />
                <span>请假</span>
              </el-col>
              <el-col :span="5" style="text-align: center">
                <el-statistic :value="attendanceStatInfo.leaveEarlyNum" :value-style="[{ 'font-size': '30px' }]" />
                <span>早退</span>
              </el-col>
              <el-col :span="4" style="text-align: center">
                <el-statistic :value="attendanceStatInfo.arriveLateNum" :value-style="[{ 'font-size': '30px' }]" />
                <span>迟到</span>
              </el-col>
            </el-row>
            <el-row style="padding-top: 20px;">
              <el-col>
                <span style="font-size: 15px; ">各班级到校出勤率排行榜</span>
              </el-col>
            </el-row>
            <el-row style="padding-top: 20px;">
              <template v-for="(val, idx) of classRankList">
                <el-col :span="2">
                  <span>{{ idx + 1 }}</span>
                </el-col>
                <el-col :span="6">
                  <span>{{ val.className }}</span>
                </el-col>
                <el-col :span="16">
                  <el-progress :percentage="val.presenceCentage" />
                </el-col>
              </template>
            </el-row>
          </div>
        </el-card>
      </el-col>
      <!-- <el-col :span="8">

      </el-col> -->
    </el-row>
  </div>
</template>

<script setup name="Index" lang="ts">
import { initWebSocket } from '@/utils/websocket';
import * as echarts from 'echarts';
import {
  indexStat,
  studentAttendanceStat,
  gradeAttendanceStat,
  studentAttendanceDayStat,
  classAttendanceDayStat,
  shiftStat,
  buildingShiftStat
} from '@/api/stat';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_stat_options, attendance_shift } = toRefs<any>(proxy?.useDict('student_stat_options', 'attendance_shift'));

const schoolStatInfo = ref<any>({});
const studentAttendanceStatInfo = ref<any>({});
const dormitoryAttendanceStatInfo = ref<any>({});
const studentStatOption = ref('start_1');
const attendanceStatInfo = ref<any>({ attendanceNum: 0 });
const classRankList = ref<any[]>([]);

const dormitoryStatOption = ref(1);
const dormitoryStatType = ref('出');
const dormitoryStatInfo = ref<any>({});
const buildingStatList = ref<any[]>([]);

const activeName = ref('student');
const studentAttendanceStatPieRef = ref();
const studentAttendanceRateLineRef = ref();
const dormitoryAttendanceStatPieRef = ref();
const dormitoryAttendanceRateLineRef = ref();

const handleClick = () => {
  if (activeName.value === 'student') {
    loadStudentAttendanceStat(studentStatOption.value);
    loadGradeAttendanceStat(studentStatOption.value);
  } else if (activeName.value === 'dormitory') {
    loadShiftStat(dormitoryStatOption.value);
    loadBuildingShiftStat(dormitoryStatOption.value);
  }
};

const loadAttendanceStatPie = (ref: any, data: any[]) => {
  let myChart: echarts.ECharts = echarts.init(ref.value);
  let option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item'
    },
    legend: [
      {
        orient: 'vertical',
        right: 'right',
        bottom: 50
      }
    ],
    label: {
      formatter: (params: Object) => {
        return params.name + ' ' + (params.percent ? params.percent : 0) + '%';
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        percentPrecision: 2,
        data: data
      }
    ]
  };
  option && myChart.setOption(option);
};

const loadAttendanceRateLine = (ref: any, xAxisData: any[], seriesData: any[], title: string) => {
  let myChart: echarts.ECharts = echarts.init(ref.value);
  let option: echarts.EChartsOption = {
    title: {
      text: title
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: seriesData,
        type: 'line'
      }
    ]
  };
  option && myChart.setOption(option);
};

const loadIndexStat = async () => {
  const res = await indexStat();
  schoolStatInfo.value = res.data;
};

const loadStudentAttendanceDayStat = async () => {
  const res = await studentAttendanceDayStat();
  attendanceStatInfo.value = res.data;
  attendanceStatInfo.value.presenceNum =
    attendanceStatInfo.value.normalNum + attendanceStatInfo.value.arriveLateNum + attendanceStatInfo.value.leaveEarlyNum;
  attendanceStatInfo.value.attendanceNum = attendanceStatInfo.value.presenceNum + attendanceStatInfo.value.absenceNum;
};

const loadClassAttendanceDayStat = async () => {
  const res = await classAttendanceDayStat();
  classRankList.value = res.data;
};

const loadStudentAttendanceStat = async (statOption: string) => {
  const res = await studentAttendanceStat(statOption);
  const stat = res.data;
  studentAttendanceStatInfo.value.attendanceNum = stat.normalNum + stat.arriveLateNum + stat.absenceNum;
  studentAttendanceStatInfo.value.presenceNum = stat.normalNum + stat.arriveLateNum;
  studentAttendanceStatInfo.value.presenceCentage = stat.presenceCentage;
  let data: any[];
  if (studentStatOption.value.startsWith('start')) {
    data = [
      { value: stat.normalNum, name: '正常' },
      { value: stat.arriveLateNum, name: '迟到' },
      { value: stat.absenceNum, name: '缺卡' },
      { value: stat.leaveNum, name: '请假' }
    ];
  } else {
    data = [
      { value: stat.normalNum, name: '正常' },
      { value: stat.leaveEarlyNum, name: '早退' },
      { value: stat.absenceNum, name: '缺卡' },
      { value: stat.leaveNum, name: '请假' }
    ];
  }
  loadAttendanceStatPie(studentAttendanceStatPieRef, data);
};

const loadGradeAttendanceStat = async (statOption: string) => {
  const res = await gradeAttendanceStat(statOption);
  const stats = res.data;
  let xAxisData: string[] = stats && stats.length > 0 ? stats.map((e) => e.gradeName) : ['无'];
  let seriesData: string[] = stats && stats.length > 0 ? stats.map((e) => e.presenceCentage) : [0];
  let title = studentStatOption.value.startsWith('start') ? '学生到校率情况' : '学生离校率情况';
  loadAttendanceRateLine(studentAttendanceRateLineRef, xAxisData, seriesData, title);
};

const loadShiftStat = async (attendanceShift: number) => {
  const res = await shiftStat(attendanceShift);
  const stat = res.data || {};
  dormitoryStatInfo.value = stat;
  if (attendanceShift % 2 === 0) {
    dormitoryStatType.value = '入';
  } else {
    dormitoryStatType.value = '出';
  }
  let data: any[];
  data = [
    { value: stat.normalCount, name: `正常人数：${stat.normalCount}` },
    { value: stat.missingCount, name: `未${dormitoryStatType.value}人数：${stat.missingCount}` },
    { value: stat.exceptionCount, name: `晚${dormitoryStatType.value}人数：${stat.exceptionCount}` },
    { value: stat.leaveCount, name: `请假人数：${stat.leaveCount}` }
  ];
  loadAttendanceStatPie(dormitoryAttendanceStatPieRef, data);
};
const loadBuildingShiftStat = async (attendanceShift: number) => {
  const res = await buildingShiftStat(attendanceShift);
  const stats = res.data;
  if (attendanceShift % 2 === 0) {
    dormitoryStatType.value = '入';
  } else {
    dormitoryStatType.value = '出';
  }
  let xAxisData: string[] = stats && stats.length > 0 ? stats.map((e) => e.buildingName) : ['无'];
  let seriesData: string[] = stats && stats.length > 0 ? stats.map((e) => e.presenceCentage) : [0];
  let title = `学生${dormitoryStatType.value}寝率情况`;
  loadAttendanceRateLine(dormitoryAttendanceRateLineRef, xAxisData, seriesData, title);
};

onMounted(() => {
  loadIndexStat();
  loadStudentAttendanceDayStat();
  loadClassAttendanceDayStat();
  loadStudentAttendanceStat(studentStatOption.value);
  loadGradeAttendanceStat(studentStatOption.value);
  loadShiftStat(dormitoryStatOption.value);
  loadBuildingShiftStat(dormitoryStatOption.value);
  let protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  initWebSocket(protocol + window.location.host + import.meta.env.VITE_APP_BASE_API + '/resource/websocket');
});

const goTarget = (url: string) => {
  window.open(url, '__blank');
};
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: 'open sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }

  .main {
    height: calc(100vh - 270px);
    .main-wrap {
      display: flex;
      :deep {
        .el-card__body {
          .demo-tabs {
            flex: 1;
          }
          display: flex;
          flex: 1;
        }
      }
      .r-title {
        color: rgb(81, 90, 110);
        font-size: 16px;
        text-align: center;
        font-weight: 600;
        padding: 10px;
        line-height: 100%;
      }
    }
  }

  .card-wrap {
    height: 110px;
    color: rgb(81, 90, 110);

    :deep {
      .el-card__body {
        height: 110px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 !important;
      }
    }

    .left-box {
      background: rgb(45, 140, 240);
      height: 100%;
      width: 40%;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 40px;
      }
    }

    .left-box1 {
      background: rgb(45, 140, 240);
    }

    .left-box2 {
      background: rgb(25, 190, 107);
    }

    .left-box3 {
      background: rgb(255, 153, 0);
    }

    .left-box4 {
      background: rgb(255, 112, 67);
    }

    .left-box5 {
      background: rgb(228, 108, 187);
    }

    .right-box {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      height: 100%;
      width: 60%;
    }
  }
}
</style>
